package com.center.growcenterserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.center.growcenterserver.common.JwtUtils;
import com.center.growcenterserver.common.R;
import com.center.growcenterserver.constant.Constants;
import com.center.growcenterserver.mapper.StudentMapper;
import com.center.growcenterserver.model.domain.Student;
import com.center.growcenterserver.model.request.StudentRequest;
import com.center.growcenterserver.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 学生服务实现类
 * </p>
 *
 * @author niit
 */
@Slf4j
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public R allStudents(IPage<Student> page) {
        IPage<Student> selectPage = studentMapper.selectPage(page, null);
        return R.success("查询成功", selectPage);
    }

    @Override
    public R deleteStudentById(String id) {
        int ret = studentMapper.deleteById(id);
        if (ret == 1) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

    @Override
    public R deleteStudentByIds(String[] ids) {
        if (ids == null || ids.toString().isEmpty()) {
            // 如果参数列表为空，直接返回 0 表示没有删除任何记录
            return R.error("请选择要删除的对象");
        }
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("student_id", ids);
        int ret = studentMapper.delete(queryWrapper);
        if (ret > 0) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

    @Override
    public R selectStudentInfo() {
        return null;
    }

//    @Override
//    public R selectStudentInfo() {
//        // 查询男女生数量
////        QueryWrapper<Student> queryWrapperFemale = new QueryWrapper<>();
////        queryWrapperFemale.eq("sex", "0"); // 假设 "0" 表示女性
////        Long femaleCount = studentMapper.selectCount(queryWrapperFemale);
////
////        QueryWrapper<Student> queryWrapperMale = new QueryWrapper<>();
////        queryWrapperMale.eq("sex", "1"); // 假设 "1" 表示男性
////        Long maleCount = studentMapper.selectCount(queryWrapperMale);
////
////        Map<String, Long> sexCount = new HashMap<>();
////        sexCount.put("femaleCount", femaleCount);
////        sexCount.put("maleCount", maleCount);
//
//        return R.success("查询成功", sexCount);
//    }

    @Override
    public int updateStudentImage(String id, String picUrl) {
        Student student = studentMapper.selectById(id);
        if (student == null) {
            throw new RuntimeException("Student not found with id: " + id);
        }
        student.setPic(picUrl);
        return studentMapper.updateById(student);
    }

    @Override
    public int addStudent(Student student) {
        return studentMapper.insert(student);
    }

    @Override
    public R updateStudent(StudentRequest studentRequest) {
        Student student = new Student();
        BeanUtils.copyProperties(studentRequest, student);
        System.out.println(student);
        if (studentMapper.updateById(student) > 0) {
            return R.success("学生信息更新成功", student);
        } else {
            return R.fatal("学生信息更新失败");
        }
    }

    public R loginWithToken(StudentRequest loginRequest, HttpSession session) {
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();
        password = DigestUtils.md5DigestAsHex((Constants.SALT + password).getBytes(StandardCharsets.UTF_8));

        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("password", password);

        if (studentMapper.selectCount(queryWrapper) > 0) {
            session.setAttribute("username", username);
            String tokenStr = JwtUtils.generateToken(username);

            // 查询用户信息，假设username是唯一的，所以使用eq进行精确匹配
            Student student = studentMapper.selectOne(new QueryWrapper<Student>().eq("username", username));

            // 封装用户信息和token到一个Map或自定义对象中，以便一并返回
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("token", tokenStr);
            resultMap.put("userInfo", student);

            return R.success("登录成功", resultMap);

        } else {
            return R.error("用户名或密码错误");
        }
    }


}